import {createSlice, PayloadAction} from "@reduxjs/toolkit";
import {RootState} from "../store";


export interface BasicInfoSlice {
    name: string;
    phoneNumber: string;
    gender: string;
    age: string;
    email: string;
    // 所在地
    location: string;
    // 参加工作时间
    inWorkDate: string;
    // 是否显示头像
    displayAvatar: boolean;
    // 民族
    ethnic: string;
    // 政治面貌
    thePoliticalLandscape: string
    // 身高体重
    height: string; weight: string
}

export type InfoItem<T , K extends keyof T> = {
        infoKey: K
        value: T[K]
        defaultValue: T[K]
        display: boolean
}
type BasicInfoList<T> = InfoItem<T, keyof T> []
export const basicInitialState: BasicInfoList<BasicInfoSlice> =  [
    { infoKey: 'name', value: '', defaultValue: '姓名', display: true },
    { infoKey: 'gender', value: '', defaultValue: '性别', display: true },
    { infoKey: 'age', value: '', defaultValue: '年龄', display: true },
    { infoKey: 'location', value: '', defaultValue: '所在地', display: true },
    { infoKey: 'phoneNumber', value: '', defaultValue: '手机号', display: true },
    { infoKey: 'email', value: '', defaultValue: '邮箱', display: true },
    { infoKey: 'inWorkDate', value: '', defaultValue: '参加工作时间', display: true },
    { infoKey: 'ethnic', value: '', defaultValue: '民族', display: false },
    { infoKey: 'thePoliticalLandscape', value: '', defaultValue: '政治面貌', display: false},
    { infoKey: 'weight', value: '', defaultValue: '体重', display: false },
    { infoKey: 'height', value: '', defaultValue: '身高', display: false },
    { infoKey: 'displayAvatar', value: true, defaultValue: true, display: true },
]


const basicInfoSlice = createSlice({
    initialState: basicInitialState,
    name: 'bcInfo',
    reducers: {
        reInitialBasicInfo: (state, action) => {
            return action.payload;
        },
        saveBasicInfo: (state, action: PayloadAction<Partial<BasicInfoSlice>>) => {
            const updateKeys = Object.keys(action.payload)
            state.filter(({infoKey}) => { return updateKeys.includes(infoKey) })
                .forEach(info => {
                    info.value = action.payload[info.infoKey] || '';
                })
        },
        changeDisplayByInfoKeys: (state, action: PayloadAction<{[p in keyof BasicInfoSlice]: boolean}>) => {
            for (const st of state) {
                st.display = action.payload[st.infoKey]
            }
        },
        displayAvatar: (state, action: PayloadAction<boolean>) => {
            state.find(d => d.infoKey === 'displayAvatar')!.value = action.payload
        }
    }
})
export const { saveBasicInfo, changeDisplayByInfoKeys, displayAvatar, reInitialBasicInfo } = basicInfoSlice.actions;

export const getBasicInfoValue = (st: RootState) => st.basic

export default basicInfoSlice.reducer;
